#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Date: 2022/6/19 15:26
Desc: 东方财富网-行情首页-沪深京 A 股
"""
import requests
import pandas as pd
import math
from functools import lru_cache
import time
import pandas as pd
import requests
import json
from datetime import datetime
from decimal import Decimal
from typing import List, Optional

NOW_API = "http://qt.gtimg.cn/q=%s"

def get_now(codes: str) -> pd.DataFrame:
    """
    获取实时股票数据并返回DataFrame

    Args:
        codes: 股票代码字符串，多个代码用逗号分隔

    Returns:
        pd.DataFrame: 包含股票实时数据的DataFrame
    """
    # 转换股票代码
    api_code = convert_code(codes)
    api_url = NOW_API % api_code

    # 发送HTTP请求
    try:
        response = requests.get(api_url, timeout=10)
        response.encoding = 'gbk'  # 腾讯接口通常使用GBK编码
        api_result = response.text
    except Exception as e:
        raise Exception(f"HTTP请求失败: {e}")

    # 清理和分割数据
    api_result = api_result.replace('\n', '')
    api_result_array = [item for item in api_result.split(';') if item.strip()]

    # 解析每条股票数据
    stock_data_list = []
    for item in api_result_array:
        if not item.strip():
            continue

        try:
            if '_' in codes:
                stock_data = _now_to_stock_day_value(item)
            else:
                stock_data = _now_to_stock_day_value2(item)
            stock_data_list.append(stock_data)
        except Exception as e:
            print(f"解析股票数据失败: {item}, 错误: {e}")
            continue

    # 转换为DataFrame
    if stock_data_list:
        df = pd.DataFrame(stock_data_list)
        return df
    else:
        return pd.DataFrame()  # 返回空DataFrame

def _now_to_stock_day_value2(now_str: str) -> dict:
    """
    解析单条股票实时数据（对应Java中的nowToStockDayValue2方法）
    """
    # 初始化默认数据
    stock_data = {
        'open': Decimal('0'),
        'high': Decimal('0'),
        'close': Decimal('0'),
        'low': Decimal('0'),
        'volume': Decimal('0'),
        'chp': Decimal('0'),
    }

    try:
        # 提取数据部分
        if '=' not in now_str:
            return stock_data

        split_str = now_str.split('=')[1].replace('"', '').replace(';', '')
        split_str_arr = split_str.split('~')

        if len(split_str_arr) < 35:
            return stock_data

        # 设置当前日期
        cur_date = datetime.now().strftime('%Y-%m-%d')
        stock_data['day'] = pd.to_datetime(cur_date)
        stock_data['date'] = pd.to_datetime(cur_date)

        # 设置股票名称和价格数据
        #stock_data['stockName'] = split_str_arr[1] if len(split_str_arr) > 1 else ''

        if len(split_str_arr) > 5 and split_str_arr[5]:
            stock_data['open'] = Decimal(split_str_arr[5])

        if len(split_str_arr) > 3 and split_str_arr[3]:
            stock_data['close'] = Decimal(split_str_arr[3])

        if len(split_str_arr) > 33 and split_str_arr[33]:
            stock_data['high'] = Decimal(split_str_arr[33])

        if len(split_str_arr) > 34 and split_str_arr[34]:
            stock_data['low'] = Decimal(split_str_arr[34])

        # 涨跌幅
        if len(split_str_arr) > 32 and split_str_arr[32]:
            stock_data['chp'] =split_str_arr[32]

        # 成交量（手）
        if len(split_str_arr) > 6 and split_str_arr[6]:
            try:
                volume = Decimal(split_str_arr[6])
                stock_data['volume'] = volume*100
            except:
                pass


    except Exception as e:
        print(f"解析股票数据详细失败: {e}")

    return stock_data

def _now_to_stock_day_value(now_str: str) -> dict:
    """
    解析单条股票实时数据（对应Java中的nowToStockDayValue2方法）
    """
    # 初始化默认数据
    stock_data = {
        'open': Decimal('0'),
        'high': Decimal('0'),
        'close': Decimal('0'),
        'low': Decimal('0'),
        'volume': Decimal('0'),
        'chp': Decimal('0'),
    }

    try:
        # 提取数据部分
        if '=' not in now_str:
            return stock_data

        split_str = now_str.split('=')[1].replace('"', '').replace(';', '')
        split_str_arr = split_str.split('~')

        if len(split_str_arr) < 8:
            return stock_data

        # 设置当前日期
        cur_date = datetime.now().strftime('%Y-%m-%d')
        stock_data['day'] = pd.to_datetime(cur_date)
        stock_data['date'] = pd.to_datetime(cur_date)

        # 设置股票名称和价格数据
        #stock_data['stockName'] = split_str_arr[1] if len(split_str_arr) > 1 else ''

        if len(split_str_arr) > 5 and split_str_arr[5]:
            stock_data['open'] = Decimal(split_str_arr[5])

        if len(split_str_arr) > 3 and split_str_arr[3]:
            stock_data['close'] = Decimal(split_str_arr[3])

        if len(split_str_arr) > 33 and split_str_arr[33]:
            stock_data['high'] = Decimal(split_str_arr[33])

        if len(split_str_arr) > 34 and split_str_arr[34]:
            stock_data['low'] = Decimal(split_str_arr[34])

        # 涨跌幅
        if len(split_str_arr) > 5 and split_str_arr[5]:
            stock_data['chp'] =split_str_arr[5]

        # 成交量（手）
        if len(split_str_arr) > 7 and split_str_arr[7]:
            try:
                volume = Decimal(split_str_arr[7])
                stock_data['volume'] = volume
            except:
                pass


    except Exception as e:
        print(f"解析股票数据详细失败: {e}")

    return stock_data

def merge_unique_dates(existing_df, new_df, date_column='date'):
    """
    简化的唯一日期追加方法
    """
    # 找出新DataFrame中唯一的记录
    mask = ~new_df[date_column].isin(existing_df[date_column])
    new_unique = new_df[mask]

    # 如果没有新记录，直接返回原DataFrame
    if new_unique.empty:
        return existing_df

    # 合并
    return pd.concat([existing_df, new_unique], ignore_index=True)

def get_count():
    # 基础URL
    base_url = "https://push2.eastmoney.com/api/qt/ulist/get?fltt=1&invt=2&cb=a&fields=f12%2Cf13%2Cf14%2Cf1%2Cf2%2Cf4%2Cf3%2Cf152%2Cf6%2Cf104%2Cf105%2Cf106&secids=1.000001%2C0.399001&ut=fa5fd1943c7b386f172d6893dbfba10b&pn=1&np=1&pz=20&dect=1&wbp2u=%7C0%7C0%7C0%7Cweb&_="

    # 添加时间戳防止缓存
    url = base_url + str(int(time.time() * 1000))

    try:
        # 发送GET请求[7,8](@ref)
        response = requests.get(url)
        response.raise_for_status()  # 检查请求是否成功[8](@ref)

        # 获取响应文本并处理JSONP格式[9](@ref)
        json_response = response.text
        json_response = json_response.replace("a(", "", 1)  # 移除开头的"a("
        json_response = json_response.rsplit(")", 1)[0]  # 移除末尾的")"

        # 解析JSON[9,10](@ref)
        data = json.loads(json_response)

        # 获取diff数组
        json_array = data["data"]["diff"]

        # 初始化计数器
        up = 0
        eq = 0
        down = 0

        # 遍历数组并累加值
        for item in json_array:
            up += item.get("f104", 0)
            eq += item.get("f106", 0)
            down += item.get("f105", 0)

        # 返回结果字典
        result_map = {
            "up": up,
            "eq": eq,
            "down": down
        }

        return result_map

    except requests.exceptions.RequestException as e:
        print(f"请求出错: {e}")
        return None
    except json.JSONDecodeError as e:
        print(f"JSON解析出错: {e}")
        return None
    except KeyError as e:
        print(f"键错误: {e}")
        return None

def get_kline_data_sina(code: str, scale: int = 240, limit: int = 1023) -> pd.DataFrame:
    """
    从新浪财经API获取K线数据并返回DataFrame
    
    参数:
    code: 股票代码 (如: '000001', '600000'等)
    scale: K线周期，240表示日线 [9](@ref)
    limit: 获取数据长度，最大1023 [7](@ref)
    
    返回:
    pd.DataFrame: 包含K线数据的DataFrame
    """
    try:
        # 转换股票代码格式
        converted_code = convert_code(code)

        # 构建API URL [9](@ref)
        api_url = f"https://money.finance.sina.com.cn/quotes_service/api/jsonp_v2.php/a=/CN_MarketData.getKLineData?symbol={converted_code}&scale={scale}&ma=no&datalen={limit}"

        # 发送HTTP请求
        response = requests.get(api_url, timeout=10)
        response.raise_for_status()

        # 处理JSONP响应格式 [9](@ref)
        result_text = response.text

        # 移除JSONP包装器
        if '/*' in result_text:
            filter_result = result_text.split('*/')[1]
        else:
            filter_result = result_text

        filter_result = filter_result.replace('a=(', '')
        if filter_result.endswith(');'):
            filter_result = filter_result[:-2]
        elif filter_result.endswith(');\n'):
            filter_result = filter_result[:-3]

        # 解析JSON数据
        json_data = json.loads(filter_result)
        
        # 转换为DataFrame
        df = pd.DataFrame(json_data)
        #取最新数据
        if not df['day'].isin([datetime.now().strftime('%Y-%m-%d')]).any():
            ndf=get_now(code)
            if not ndf.empty:
                df=merge_unique_dates(ndf,df, date_column='day')

        # 数据类型转换
        if not df.empty:
            # 转换数值列
            numeric_columns = ['open', 'high', 'low', 'close', 'volume']
            for col in numeric_columns:
                if col in df.columns:
                    df[col] = pd.to_numeric(df[col], errors='coerce')

            # 转换日期列
            if 'day' in df.columns:
                df['day'] = pd.to_datetime(df['day'])
                df['date'] = pd.to_datetime(df['day'])
                df.index = pd.to_datetime( df['date'])
                df.reset_index(inplace=True, drop=True)
                df = df.sort_values('day')  # 按日期排序

        # 计算涨幅百分比 (chp) 
        # 涨幅 = (今日收盘价 - 昨日收盘价) / 昨日收盘价 × 100% [7,8](@ref)
        if 'close' in df.columns:
            # 计算每日涨跌幅
            df['chp'] = df['close'].pct_change() * 100
            # 保留两位小数
            df['chp'] = df['chp'].round(2)
            # 第一行没有前一日数据，设置为NaN或0
            if pd.isna(df.loc[df.index[0], 'chp']):
                df.loc[df.index[0], 'chp'] = 0.0


                # 限制返回行数
        if len(df) > limit:
            df = df.tail(limit)


        return df

    except Exception as e:
        print(f"获取K线数据时出错: {e}")
        return pd.DataFrame()

def convert_code(code: str) -> str:
    """
    转换股票代码格式 [9](@ref)
    
    参数:
    code: 原始股票代码
    
    返回:
    str: 转换后的代码格式 (如: sh600000, sz000001)
    """
    if len(code) == 6:
        if code.startswith(('5', '6', '9')):
            return 'sh' + code
        else:
            return 'sz' + code
    return code

def stock_zh_a_spot_em() -> pd.DataFrame:
    """
    东方财富网-沪深京 A 股-实时行情
    https://quote.eastmoney.com/center/gridlist.html#hs_a_board
    :return: 实时行情
    :rtype: pandas.DataFrame
    """
    url = "http://82.push2.eastmoney.com/api/qt/clist/get"
    page_size = 50
    page_current = 1
    params = {
        "pn": page_current,
        "pz": page_size,
        "po": "1",
        "np": "1",
        "ut": "bd1d9ddb04089700cf9c27f6f7426281",
        "fltt": "2",
        "invt": "2",
        "fid": "f12",
        "fs": "m:0 t:6,m:0 t:80,m:1 t:2,m:1 t:23,m:0 t:81 s:2048",
        "fields": "f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f14,f15,f16,f17,f18,f20,f21,f22,f23,f24,f25,f26,f37,f38,f39,f40,f41,f45,f46,f48,f49,f57,f61,f100,f112,f113,f114,f115,f221",
        "_": "1623833739532",
    }
    r = requests.get(url, params=params)
    data_json = r.json()
    data = data_json["data"]["diff"]
    if not data:
        return pd.DataFrame()

    data_count = data_json["data"]["total"]
    page_count = math.ceil(data_count/page_size)
    while page_count > 1:
        page_current = page_current + 1
        params["pn"] = page_current
        r = requests.get(url, params=params)
        data_json = r.json()
        _data = data_json["data"]["diff"]
        data.extend(_data)
        page_count =page_count - 1

    temp_df = pd.DataFrame(data)
    temp_df.columns = [
        "最新价",
        "涨跌幅",
        "涨跌额",
        "成交量",
        "成交额",
        "振幅",
        "换手率",
        "市盈率动",
        "量比",
        "5分钟涨跌",
        "代码",
        "名称",
        "最高",
        "最低",
        "今开",
        "昨收",
        "总市值",
        "流通市值",
        "涨速",
        "市净率",
        "60日涨跌幅",
        "年初至今涨跌幅",
        "上市时间",
        "加权净资产收益率",
        "总股本",
        "已流通股份",
        "营业收入",
        "营业收入同比增长",
        "归属净利润",
        "归属净利润同比增长",
        "每股未分配利润",
        "毛利率",
        "资产负债率",
        "每股公积金",
        "所处行业",
        "每股收益",
        "每股净资产",
        "市盈率静",
        "市盈率TTM",
        "报告期"
    ]
    temp_df = temp_df[
        [
            "代码",
            "名称",
            "最新价",
            "涨跌幅",
            "涨跌额",
            "成交量",
            "成交额",
            "振幅",
            "换手率",
            "量比",
            "今开",
            "最高",
            "最低",
            "昨收",
            "涨速",
            "5分钟涨跌",
            "60日涨跌幅",
            "年初至今涨跌幅",
            "市盈率动",
            "市盈率TTM",
            "市盈率静",
            "市净率",
            "每股收益",
            "每股净资产",
            "每股公积金",
            "每股未分配利润",
            "加权净资产收益率",
            "毛利率",
            "资产负债率",
            "营业收入",
            "营业收入同比增长",
            "归属净利润",
            "归属净利润同比增长",
            "报告期",
            "总股本",
            "已流通股份",
            "总市值",
            "流通市值",
            "所处行业",
            "上市时间"
        ]
    ]
    temp_df["最新价"] = pd.to_numeric(temp_df["最新价"], errors="coerce")
    temp_df["涨跌幅"] = pd.to_numeric(temp_df["涨跌幅"], errors="coerce")
    temp_df["涨跌额"] = pd.to_numeric(temp_df["涨跌额"], errors="coerce")
    temp_df["成交量"] = pd.to_numeric(temp_df["成交量"], errors="coerce")
    temp_df["成交额"] = pd.to_numeric(temp_df["成交额"], errors="coerce")
    temp_df["振幅"] = pd.to_numeric(temp_df["振幅"], errors="coerce")
    temp_df["量比"] = pd.to_numeric(temp_df["量比"], errors="coerce")
    temp_df["换手率"] = pd.to_numeric(temp_df["换手率"], errors="coerce")
    temp_df["最高"] = pd.to_numeric(temp_df["最高"], errors="coerce")
    temp_df["最低"] = pd.to_numeric(temp_df["最低"], errors="coerce")
    temp_df["今开"] = pd.to_numeric(temp_df["今开"], errors="coerce")
    temp_df["昨收"] = pd.to_numeric(temp_df["昨收"], errors="coerce")
    temp_df["涨速"] = pd.to_numeric(temp_df["涨速"], errors="coerce")
    temp_df["5分钟涨跌"] = pd.to_numeric(temp_df["5分钟涨跌"], errors="coerce")
    temp_df["60日涨跌幅"] = pd.to_numeric(temp_df["60日涨跌幅"], errors="coerce")
    temp_df["年初至今涨跌幅"] = pd.to_numeric(temp_df["年初至今涨跌幅"], errors="coerce")
    temp_df["市盈率动"] = pd.to_numeric(temp_df["市盈率动"], errors="coerce")
    temp_df["市盈率TTM"] = pd.to_numeric(temp_df["市盈率TTM"], errors="coerce")
    temp_df["市盈率静"] = pd.to_numeric(temp_df["市盈率静"], errors="coerce")
    temp_df["市净率"] = pd.to_numeric(temp_df["市净率"], errors="coerce")
    temp_df["每股收益"] = pd.to_numeric(temp_df["每股收益"], errors="coerce")
    temp_df["每股净资产"] = pd.to_numeric(temp_df["每股净资产"], errors="coerce")
    temp_df["每股公积金"] = pd.to_numeric(temp_df["每股公积金"], errors="coerce")
    temp_df["每股未分配利润"] = pd.to_numeric(temp_df["每股未分配利润"], errors="coerce")
    temp_df["加权净资产收益率"] = pd.to_numeric(temp_df["加权净资产收益率"], errors="coerce")
    temp_df["毛利率"] = pd.to_numeric(temp_df["毛利率"], errors="coerce")
    temp_df["资产负债率"] = pd.to_numeric(temp_df["资产负债率"], errors="coerce")
    temp_df["营业收入"] = pd.to_numeric(temp_df["营业收入"], errors="coerce")
    temp_df["营业收入同比增长"] = pd.to_numeric(temp_df["营业收入同比增长"], errors="coerce")
    temp_df["归属净利润"] = pd.to_numeric(temp_df["归属净利润"], errors="coerce")
    temp_df["归属净利润同比增长"] = pd.to_numeric(temp_df["归属净利润同比增长"], errors="coerce")
    temp_df["报告期"] = pd.to_datetime(temp_df["报告期"], format='%Y%m%d', errors="coerce")
    temp_df["总股本"] = pd.to_numeric(temp_df["总股本"], errors="coerce")
    temp_df["已流通股份"] = pd.to_numeric(temp_df["已流通股份"], errors="coerce")
    temp_df["总市值"] = pd.to_numeric(temp_df["总市值"], errors="coerce")
    temp_df["流通市值"] = pd.to_numeric(temp_df["流通市值"], errors="coerce")
    temp_df["上市时间"] = pd.to_datetime(temp_df["上市时间"], format='%Y%m%d', errors="coerce")

    return temp_df


@lru_cache()
def code_id_map_em() -> dict:
    """
    东方财富-股票和市场代码
    http://quote.eastmoney.com/center/gridlist.html#hs_a_board
    :return: 股票和市场代码
    :rtype: dict
    """
    url = "http://80.push2.eastmoney.com/api/qt/clist/get"
    page_size = 50
    page_current = 1
    params = {
        "pn": page_current,
        "pz": page_size,
        "po": "1",
        "np": "1",
        "ut": "bd1d9ddb04089700cf9c27f6f7426281",
        "fltt": "2",
        "invt": "2",
        "fid": "f12",
        "fs": "m:1 t:2,m:1 t:23",
        "fields": "f12",
        "_": "1623833739532",
    }
    r = requests.get(url, params=params)
    data_json = r.json()
    data = data_json["data"]["diff"]
    if not data:
        return dict()

    data_count = data_json["data"]["total"]
    page_count = math.ceil(data_count/page_size)
    while page_count > 1:
        page_current = page_current + 1
        params["pn"] = page_current
        r = requests.get(url, params=params)
        data_json = r.json()
        _data = data_json["data"]["diff"]
        data.extend(_data)
        page_count =page_count - 1

    temp_df = pd.DataFrame(data)
    temp_df["market_id"] = 1
    temp_df.columns = ["sh_code", "sh_id"]
    code_id_dict = dict(zip(temp_df["sh_code"], temp_df["sh_id"]))
    page_current = 1
    params = {
        "pn": page_current,
        "pz": page_size,
        "po": "1",
        "np": "1",
        "ut": "bd1d9ddb04089700cf9c27f6f7426281",
        "fltt": "2",
        "invt": "2",
        "fid": "f12",
        "fs": "m:0 t:6,m:0 t:80",
        "fields": "f12",
        "_": "1623833739532",
    }
    r = requests.get(url, params=params)
    data_json = r.json()
    data = data_json["data"]["diff"]
    if not data:
        return dict()

    data_count = data_json["data"]["total"]
    page_count = math.ceil(data_count/page_size)
    while page_count > 1:
        page_current = page_current + 1
        params["pn"] = page_current
        r = requests.get(url, params=params)
        data_json = r.json()
        _data = data_json["data"]["diff"]
        data.extend(_data)
        page_count =page_count - 1

    temp_df_sz = pd.DataFrame(data)
    temp_df_sz["sz_id"] = 0
    code_id_dict.update(dict(zip(temp_df_sz["f12"], temp_df_sz["sz_id"])))
    page_current = 1
    params = {
        "pn": page_current,
        "pz": page_size,
        "po": "1",
        "np": "1",
        "ut": "bd1d9ddb04089700cf9c27f6f7426281",
        "fltt": "2",
        "invt": "2",
        "fid": "f12",
        "fs": "m:0 t:81 s:2048",
        "fields": "f12",
        "_": "1623833739532",
    }
    r = requests.get(url, params=params)
    data_json = r.json()
    data = data_json["data"]["diff"]
    if not data:
        return dict()

    data_count = data_json["data"]["total"]
    page_count = math.ceil(data_count/page_size)
    while page_count > 1:
        page_current = page_current + 1
        params["pn"] = page_current
        r = requests.get(url, params=params)
        data_json = r.json()
        _data = data_json["data"]["diff"]
        data.extend(_data)
        page_count =page_count - 1

    temp_df_sz = pd.DataFrame(data)
    temp_df_sz["bj_id"] = 0
    code_id_dict.update(dict(zip(temp_df_sz["f12"], temp_df_sz["bj_id"])))
    return code_id_dict


def stock_zh_a_hist(
        symbol: str = "000001",
        period: str = "daily",
        start_date: str = "19700101",
        end_date: str = "20500101",
        adjust: str = "",
) -> pd.DataFrame:
    """
    东方财富网-行情首页-沪深京 A 股-每日行情
    https://quote.eastmoney.com/concept/sh603777.html?from=classic
    :param symbol: 股票代码
    :type symbol: str
    :param period: choice of {'daily', 'weekly', 'monthly'}
    :type period: str
    :param start_date: 开始日期
    :type start_date: str
    :param end_date: 结束日期
    :type end_date: str
    :param adjust: choice of {"qfq": "前复权", "hfq": "后复权", "": "不复权"}
    :type adjust: str
    :return: 每日行情
    :rtype: pandas.DataFrame
    """
    code_id_dict = code_id_map_em()
    adjust_dict = {"qfq": "1", "hfq": "2", "": "0"}
    period_dict = {"daily": "101", "weekly": "102", "monthly": "103"}
    url = "http://push2his.eastmoney.com/api/qt/stock/kline/get"
    params = {
        "fields1": "f1,f2,f3,f4,f5,f6",
        "fields2": "f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61,f116",
        "ut": "7eea3edcaed734bea9cbfc24409ed989",
        "klt": period_dict[period],
        "fqt": adjust_dict[adjust],
        "secid": f"{code_id_dict[symbol]}.{symbol}",
        "beg": start_date,
        "end": end_date,
        "_": "1623766962675",
    }
    r = requests.get(url, params=params)
    data_json = r.json()
    if not (data_json["data"] and data_json["data"]["klines"]):
        return pd.DataFrame()
    temp_df = pd.DataFrame(
        [item.split(",") for item in data_json["data"]["klines"]]
    )
    temp_df.columns = [
        "日期",
        "开盘",
        "收盘",
        "最高",
        "最低",
        "成交量",
        "成交额",
        "振幅",
        "涨跌幅",
        "涨跌额",
        "换手率",
    ]
    temp_df.index = pd.to_datetime(temp_df["日期"])
    temp_df.reset_index(inplace=True, drop=True)

    temp_df["开盘"] = pd.to_numeric(temp_df["开盘"])
    temp_df["收盘"] = pd.to_numeric(temp_df["收盘"])
    temp_df["最高"] = pd.to_numeric(temp_df["最高"])
    temp_df["最低"] = pd.to_numeric(temp_df["最低"])
    temp_df["成交量"] = pd.to_numeric(temp_df["成交量"])
    temp_df["成交额"] = pd.to_numeric(temp_df["成交额"])
    temp_df["振幅"] = pd.to_numeric(temp_df["振幅"])
    temp_df["涨跌幅"] = pd.to_numeric(temp_df["涨跌幅"])
    temp_df["涨跌额"] = pd.to_numeric(temp_df["涨跌额"])
    temp_df["换手率"] = pd.to_numeric(temp_df["换手率"])

    return temp_df


def stock_zh_a_hist_min_em(
        symbol: str = "000001",
        start_date: str = "1979-09-01 09:32:00",
        end_date: str = "2222-01-01 09:32:00",
        period: str = "5",
        adjust: str = "",
) -> pd.DataFrame:
    """
    东方财富网-行情首页-沪深京 A 股-每日分时行情
    https://quote.eastmoney.com/concept/sh603777.html?from=classic
    :param symbol: 股票代码
    :type symbol: str
    :param start_date: 开始日期
    :type start_date: str
    :param end_date: 结束日期
    :type end_date: str
    :param period: choice of {'1', '5', '15', '30', '60'}
    :type period: str
    :param adjust: choice of {'', 'qfq', 'hfq'}
    :type adjust: str
    :return: 每日分时行情
    :rtype: pandas.DataFrame
    """
    code_id_dict = code_id_map_em()
    adjust_map = {
        "": "0",
        "qfq": "1",
        "hfq": "2",
    }
    if period == "1":
        url = "https://push2his.eastmoney.com/api/qt/stock/trends2/get"
        params = {
            "fields1": "f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13",
            "fields2": "f51,f52,f53,f54,f55,f56,f57,f58",
            "ut": "7eea3edcaed734bea9cbfc24409ed989",
            "ndays": "5",
            "iscr": "0",
            "secid": f"{code_id_dict[symbol]}.{symbol}",
            "_": "1623766962675",
        }
        r = requests.get(url, params=params)
        data_json = r.json()
        temp_df = pd.DataFrame(
            [item.split(",") for item in data_json["data"]["trends"]]
        )
        temp_df.columns = [
            "时间",
            "开盘",
            "收盘",
            "最高",
            "最低",
            "成交量",
            "成交额",
            "最新价",
        ]
        temp_df.index = pd.to_datetime(temp_df["时间"])
        temp_df = temp_df[start_date:end_date]
        temp_df.reset_index(drop=True, inplace=True)
        temp_df["开盘"] = pd.to_numeric(temp_df["开盘"])
        temp_df["收盘"] = pd.to_numeric(temp_df["收盘"])
        temp_df["最高"] = pd.to_numeric(temp_df["最高"])
        temp_df["最低"] = pd.to_numeric(temp_df["最低"])
        temp_df["成交量"] = pd.to_numeric(temp_df["成交量"])
        temp_df["成交额"] = pd.to_numeric(temp_df["成交额"])
        temp_df["最新价"] = pd.to_numeric(temp_df["最新价"])
        temp_df["时间"] = pd.to_datetime(temp_df["时间"]).astype(str)
        return temp_df
    else:
        url = "http://push2his.eastmoney.com/api/qt/stock/kline/get"
        params = {
            "fields1": "f1,f2,f3,f4,f5,f6",
            "fields2": "f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61",
            "ut": "7eea3edcaed734bea9cbfc24409ed989",
            "klt": period,
            "fqt": adjust_map[adjust],
            "secid": f"{code_id_dict[symbol]}.{symbol}",
            "beg": "0",
            "end": "20500000",
            "_": "1630930917857",
        }
        r = requests.get(url, params=params)
        data_json = r.json()
        temp_df = pd.DataFrame(
            [item.split(",") for item in data_json["data"]["klines"]]
        )
        temp_df.columns = [
            "时间",
            "开盘",
            "收盘",
            "最高",
            "最低",
            "成交量",
            "成交额",
            "振幅",
            "涨跌幅",
            "涨跌额",
            "换手率",
        ]
        temp_df.index = pd.to_datetime(temp_df["时间"])
        temp_df = temp_df[start_date:end_date]
        temp_df.reset_index(drop=True, inplace=True)
        temp_df["开盘"] = pd.to_numeric(temp_df["开盘"])
        temp_df["收盘"] = pd.to_numeric(temp_df["收盘"])
        temp_df["最高"] = pd.to_numeric(temp_df["最高"])
        temp_df["最低"] = pd.to_numeric(temp_df["最低"])
        temp_df["成交量"] = pd.to_numeric(temp_df["成交量"])
        temp_df["成交额"] = pd.to_numeric(temp_df["成交额"])
        temp_df["振幅"] = pd.to_numeric(temp_df["振幅"])
        temp_df["涨跌幅"] = pd.to_numeric(temp_df["涨跌幅"])
        temp_df["涨跌额"] = pd.to_numeric(temp_df["涨跌额"])
        temp_df["换手率"] = pd.to_numeric(temp_df["换手率"])
        temp_df["时间"] = pd.to_datetime(temp_df["时间"]).astype(str)
        temp_df = temp_df[
            [
                "时间",
                "开盘",
                "收盘",
                "最高",
                "最低",
                "涨跌幅",
                "涨跌额",
                "成交量",
                "成交额",
                "振幅",
                "换手率",
            ]
        ]
        return temp_df


def stock_zh_a_hist_pre_min_em(
        symbol: str = "000001",
        start_time: str = "09:00:00",
        end_time: str = "15:50:00",
) -> pd.DataFrame:
    """
    东方财富网-行情首页-沪深京 A 股-每日分时行情包含盘前数据
    http://quote.eastmoney.com/concept/sh603777.html?from=classic
    :param symbol: 股票代码
    :type symbol: str
    :param start_time: 开始时间
    :type start_time: str
    :param end_time: 结束时间
    :type end_time: str
    :return: 每日分时行情包含盘前数据
    :rtype: pandas.DataFrame
    """
    code_id_dict = code_id_map_em()
    url = "https://push2.eastmoney.com/api/qt/stock/trends2/get"
    params = {
        "fields1": "f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13",
        "fields2": "f51,f52,f53,f54,f55,f56,f57,f58",
        "ut": "fa5fd1943c7b386f172d6893dbfba10b",
        "ndays": "1",
        "iscr": "1",
        "iscca": "0",
        "secid": f"{code_id_dict[symbol]}.{symbol}",
        "_": "1623766962675",
    }
    r = requests.get(url, params=params)
    data_json = r.json()
    temp_df = pd.DataFrame(
        [item.split(",") for item in data_json["data"]["trends"]]
    )
    temp_df.columns = [
        "时间",
        "开盘",
        "收盘",
        "最高",
        "最低",
        "成交量",
        "成交额",
        "最新价",
    ]
    temp_df.index = pd.to_datetime(temp_df["时间"])
    date_format = temp_df.index[0].date().isoformat()
    temp_df = temp_df[
              date_format + " " + start_time : date_format + " " + end_time
              ]
    temp_df.reset_index(drop=True, inplace=True)
    temp_df["开盘"] = pd.to_numeric(temp_df["开盘"])
    temp_df["收盘"] = pd.to_numeric(temp_df["收盘"])
    temp_df["最高"] = pd.to_numeric(temp_df["最高"])
    temp_df["最低"] = pd.to_numeric(temp_df["最低"])
    temp_df["成交量"] = pd.to_numeric(temp_df["成交量"])
    temp_df["成交额"] = pd.to_numeric(temp_df["成交额"])
    temp_df["最新价"] = pd.to_numeric(temp_df["最新价"])
    temp_df["时间"] = pd.to_datetime(temp_df["时间"]).astype(str)
    return temp_df





# 使用示例
if __name__ == "__main__":
    try:
        # 获取单只或多只股票数据
        df = get_now("510300")  # 示例代码
        print(df)
        df2=get_kline_data_sina(code='510300',scale=240,limit=10)
        print(df2)

        dates = merge_unique_dates(df2,df, date_column='date')

        print(dates)
    except Exception as e:
        print(f"获取股票数据失败: {e}")